layui.use(['table', 'admin', 'ax', 'laydate', 'form'], function () {
    var $ = layui.$;
    var table = layui.table;
    var $ax = layui.ax;
    var admin = layui.admin;
    var form = layui.form;
    var laydate = layui.laydate;
// 创建地图
    var map = new AMap.Map('container', {
        zoom: 4
    });

// 加载 AMap UI 组件
    AMapUI.load(['ui/misc/PathSimplifier', 'lib/$'], function (PathSimplifier, $) {

        // 检查是否支持 Canvas
        if (!PathSimplifier.supportCanvas) {
            alert('当前环境不支持 Canvas！');
            return;
        }

        // 定义一些颜色 (参数一)
        var colors = [
            "#3366cc", "#dc3912", "#ff9900", "#109618",
            "#990099", "#0099c6", "#dd4477", "#66aa00",
            "#b82e2e", "#316395", "#994499", "#22aa99",
            "#aaaa11", "#6633cc", "#e67300", "#8b0707",
            "#651067", "#329262", "#5574a6", "#3b3eac"
        ];

        // 一、创建 PathSimplifier 实例
        var pathSimplifierIns = new PathSimplifier({
            zIndex: 100,
            map: map, // 所属的地图实例

            // 1.获取路径数据
            getPath: function (pathData, pathIndex) {
                return pathData.path;
            },

            // 2.获取悬停提示
            getHoverTitle: function (pathData, pathIndex, pointIndex) {
                if (pointIndex >= 0) {
                    // 点
                    return pathData.name + '，点:' + pointIndex + '/' + pathData.path.length;
                }
                return pathData.name + '，点数量' + pathData.path.length;
            },

            // 3.渲染选项
            renderOptions: {
                pathLineStyle: {
                    dirArrowStyle: true
                },

                getPathStyle: function (pathItem, zoom) {
                    var color = colors[pathItem.pathIndex],
                        lineWidth = Math.round(4 * Math.pow(1.1, zoom - 3));

                    return {
                        pathLineStyle: {
                            strokeStyle: color,
                            lineWidth: lineWidth
                        },
                        pathLineSelectedStyle: {
                            lineWidth: lineWidth + 2
                        },
                        pathNavigatorStyle: {
                            fillStyle: color
                        }
                    };
                }
            }
        });

        // 轨迹巡航器数组 (参数二)
        var pathNavigs = [];

        // 二、获取或创建轨迹巡航器
        function getNavg(pathIndex) {
            if (!pathNavigs[pathIndex]) {
                // 创建一个轨迹巡航器
                var navgtr = pathSimplifierIns.createPathNavigator(pathIndex, {
                    loop: true,
                    speed: parseInt($('#speedInp_' + pathIndex).val()),
                    pathNavigatorStyle: {
                        width: 24,
                        height: 48,
                        //使用图片
                        content: PathSimplifier.Render.Canvas.getImageContent("https://a.amap.com/jsapi_demos/static/demo-center-v2/car.png", onload, onerror),
                        strokeStyle: null,
                        fillStyle: null,
                        //经过路径的样式
                        pathLinePassedStyle: {
                            lineWidth: 6,
                            strokeStyle: 'black',
                            dirArrowStyle: {
                                stepSpace: 15,
                                strokeStyle: 'red'
                            }
                        }
                    }
                });

                // 创建标记信息
                var $markerContent = $('<div class="markerInfo"></div>');
                var pathData = pathSimplifierIns.getPathData(pathIndex);
                // $markerContent.html(pathSimplifierIns.getPathData(pathIndex).name);

                var nameParts = pathData.name.split('-');
                var firstPart = nameParts[0];
                var secondPart = nameParts.slice(1).join('-');

                $markerContent.html(
                    "<strong>车辆信息</strong><br/>"
                    + "货运订单号: <span style='color: red;'>" + secondPart + "</span><br/>"
                    + "车牌: <span style='color: red;'>" + firstPart + "</span><br/>"
                    // + "路线: 北京好想来中心仓 -> 浩海路门店"
                );

                // 创建标记
                navgtr.marker = new AMap.Marker({
                    offset: new AMap.Pixel(12, -10),
                    content: $markerContent.get(0),
                    map: map
                });

                // 获取消息元素
                var $msg = $('#routes-container').find('div.route-item[data-idx="' + pathIndex + '"]').find('.msg');

                // 监听移动事件
                navgtr.on('move', function () {
                    navgtr.marker.setPosition(navgtr.getPosition());
                });

                // 销毁时的回调
                navgtr.onDestroy(function () {
                    pathNavigs[pathIndex] = null;
                    navgtr.marker.setMap(null);
                    $msg.html('');
                });

                // 开始和恢复时记录开始时间和距离
                navgtr.on('start resume', function () {
                    navgtr._startTime = Date.now();
                    navgtr._startDist = this.getMovedDistance();
                });

                // 停止和暂停时更新消息
                navgtr.on('stop pause', function () {
                    navgtr._movedTime = Date.now() - navgtr._startTime;
                    navgtr._movedDist = this.getMovedDistance() - navgtr._startDist;

                    navgtr._realSpeed = (navgtr._movedDist / navgtr._movedTime * 3600);

                    var msgInfo = {
                        '状态': this.getNaviStatus(),
                        '设定速度': this.getSpeed() + ' km/h',
                        '总行进距离': Math.round(this.getMovedDistance() / 1000) + ' km',
                        '本段行进距离': Math.round(navgtr._movedDist / 1000) + ' km',
                        '本段耗时': (navgtr._movedTime / 1000) + ' s',
                        '本段实际速度': Math.round(navgtr._realSpeed) + ' km/h'
                    };

                    $msg.html('<pre>' + JSON.stringify(msgInfo, null, 2) + '</pre>');

                    refreshNavgButtons();
                });

                // 移动时更新消息
                navgtr.on('move', function () {
                    var msgInfo = {
                        '状态': this.getNaviStatus(),
                        '设定速度': this.getSpeed() + ' km/h',
                        '总行进距离': Math.round(this.getMovedDistance() / 1000) + ' km'
                    };

                    $msg.html('<pre>' + JSON.stringify(msgInfo, null, 2) + '</pre>');
                });

                pathNavigs[pathIndex] = navgtr;
            }

            return pathNavigs[pathIndex];
        }

        // 轨迹巡航按钮配置
        var navigBtnsConf = [{
            name: '开始巡航',
            action: 'start',
            enableExp: 'navgStatus === "stop" || navgStatus === "pause"'
        }, {
            name: '暂停',
            action: 'pause',
            enableExp: 'navgStatus === "moving"'
        }, {
            name: '恢复',
            action: 'resume',
            enableExp: 'navgStatus === "pause"'
        }, {
            name: '停止',
            action: 'stop',
            enableExp: 'navgStatus === "moving"'
        }, {
            name: '销毁',
            action: 'destroy',
            enableExp: 'navgExists'
        }];

        // 刷新轨迹巡航按钮状态
        function refreshNavgButtons() {
            $('#routes-container').find('div.route-item').each(function () {
                var pathIndex = parseInt($(this).attr('data-idx'), 0); // 获取路径索引
                if (pathIndex < 0) {
                    return; // 如果路径索引无效，则跳过
                }
                var navgStatus = 'stop', // 默认状态为停止
                    navgExists = !!pathNavigs[pathIndex]; // 检查是否存在该路径的巡航实例
                if (navgExists) {
                    navgStatus = pathNavigs[pathIndex].getNaviStatus(); // 获取当前的巡航状态
                }
                $(this).find('.navigBtn').each(function () {
                    var btnIdx = parseInt($(this).attr('data-btnIdx'));
                    $(this).prop('disabled', !eval(navigBtnsConf[btnIdx].enableExp)); // 根据配置启用或禁用按钮
                });
            });
        }

        // 初始化单个路径项
        function initRouteItem(pathData, idx) {
            debugger;
            // 详细信息拆分
            var nameParts = pathData.name.split('-');
            var firstPart = nameParts[0];
            var secondPart = nameParts.slice(1).join('-');

            var $routeItem = $('<div class="route-item"></div>');
            $routeItem.attr('data-idx', idx);
            $('<h3/>')
                .css({
                    color: colors[idx]
                })
                .html("车牌号: " + firstPart + "<br/>" + "货运订单号: " + secondPart)
                // .html(pathData.name + '(点数： ' + pathData.path.length + ')')
                .appendTo($routeItem)
                .on('click', function () {
                    pathSimplifierIns.setSelectedPathIndex(idx);
                });

            for (var i = 0, len = navigBtnsConf.length; i < len; i++) {
                $('<button class="navigBtn" data-btnIdx="' + i + '" data-act="' + navigBtnsConf[i].action + '"></button>')
                    .html(navigBtnsConf[i].name)
                    .appendTo($routeItem);
            }

            var $speedBox = $('<div class="speedBox"></div>').appendTo($routeItem);
            var speedTxt = $('<span></span>').appendTo($speedBox);
            var speedRangeInput = $('<input id="speedInp_' + idx + '" class="speedRange" type="range" min="100" max="100000" step="100" value="100" />').appendTo($speedBox);

            function updateSpeedTxt() {
                var speed = parseInt(speedRangeInput.val(), 10);
                speedTxt.html('时速：' + speed + ' km/h');
                if (pathNavigs[idx]) {
                    pathNavigs[idx].setSpeed(speed);
                }
            }

            speedRangeInput.on('change', updateSpeedTxt);
            updateSpeedTxt();

            $('<div class="msg"></div>').appendTo($routeItem);
            $routeItem.appendTo('#routes-container');
        }

        // 初始化路径容器
        function initRoutesContainer(data) {
            debugger;
            $('#routes-container').on('click', '.navigBtn', function () {
                var pathIndex = parseInt($(this).closest('.route-item').attr('data-idx'), 0);
                var navg = getNavg(pathIndex);
                navg[$(this).attr('data-act')]();
                refreshNavgButtons();
            });
            for (var i = 0, len = data.length; i < len; i++) {
                initRouteItem(data[i], i);
            }
            refreshNavgButtons();
        }

        // 全局变量
        window.pathSimplifierIns = pathSimplifierIns;

        // 显示加载提示
        // $('<div id="loadingTip">加载数据，请稍候...</div>').appendTo(document.body);

        // 获取路径数据
        // $.getJSON('https://a.amap.com/amap-ui/static/data/big-routes.json', function (d) {
        // $.getJSON(Feng.ctxPath + '/MapTransport/queryTrackWeb', function (d) {
        //
        //     // console.log("d", d)
        //
        //     // 移除加载提示元素
        //     $('#loadingTip').remove();
        //
        //     // 使用处理后的数据初始化路径简化器实例
        //     pathSimplifierIns.setData(d);
        //
        //     // 初始化界面上的路线容器
        //     initRoutesContainer(d);
        //
        // });

        // 清空路径数据和DOM元素的函数
        function clearOldData() {
            // 清除路径数据
            pathSimplifierIns.setData([]);

            // 清除右侧列表中的DOM元素
            $('#routes-container').empty();

            // 清除路径巡航器数组
            pathNavigs = [];
        }

        $('#searchButton').on('click', function() {
            // 清理旧数据
            clearOldData();

            var queryData = {};
            queryData['dispatchNumber'] = $("#searchInput").val();
            queryData['operateId'] = $("#searchSelect").val();

            // 发起GET请求
            $.getJSON(Feng.ctxPath + '/MapTransport/queryTrackWebNew', queryData, function(d) {

                console.log("d", d)
                // 使用处理后的数据初始化路径简化器实例
                pathSimplifierIns.setData(d);

                // 初始化界面上的路线容器
                initRoutesContainer(d);
            });
        });
});
})

